<template>
  <!--固定高，宽-->
  <div class="app-container"  style="overflow-x: hidden;overflow-y: hidden;">

    <el-autocomplete
      v-model="mapLocation.address"
      :fetch-suggestions="querySearch"
      placeholder="请输入详细地址"
      style="width: 30%;margin:8px 450px"
      :trigger-on-focus="false"
      @select="handleSelect"
    />
    <div style="margin: 1px">
      <baidu-map class="bm-view" :center="mapCenter" :zoom="mapZoom" :scroll-wheel-zoom="true" ak="baidu-ak" @ready="handlerBMap" />

    </div>

  </div>
</template>

<script>
  import BaiduMap from 'vue-baidu-map/components/map/Map.vue'
  export default {
    name: 'Map',
    components: {
      BaiduMap
    },
    data() {
      return {

        mapZoom: 15,
        mapCenter: { lng: 118.38, lat: 31.33 },
        mapLocation: {
          address: undefined,
          coordinate: undefined
        }
      }
    },
    methods: {
      handlerBMap({ BMap, map }) {
        this.BMap = BMap
        this.map = map
        if (this.mapLocation.coordinate && this.mapLocation.coordinate.lng) {
          this.mapCenter.lng = this.mapLocation.coordinate.lng
          this.mapCenter.lat = this.mapLocation.coordinate.lat
          this.mapZoom = 15
          map.addOverlay(new this.BMap.Marker(this.mapLocation.coordinate))
        } else {
          this.mapCenter.lng = 118.38
          this.mapCenter.lat = 31.33
          this.mapZoom = 10
        }
      },
      querySearch(queryString, cb) {
        var that = this
        var myGeo = new this.BMap.Geocoder()
        myGeo.getPoint(queryString, function(point) {
          if (point) {
            that.mapLocation.coordinate = point
            that.makerCenter(point)
          } else {
            that.mapLocation.coordinate = null
          }
        }, this.locationCity)
        var options = {
          onSearchComplete: function(results) {
            if (local.getStatus() === 0) {
              // 判断状态是否正确
              var s = []
              for (var i = 0; i < results.getCurrentNumPois(); i++) {
                var x = results.getPoi(i)
                var item = { value: x.address + x.title, point: x.point }
                s.push(item)
                cb(s)
              }
            } else {
              cb()
            }
          }
        }
        var local = new this.BMap.LocalSearch(this.map, options)
        local.search(queryString)
      },
      handleSelect(item) {
        var { point } = item
        this.mapLocation.coordinate = point
        this.makerCenter(point)
      },
      makerCenter(point) {
        if (this.map) {
          this.map.clearOverlays()
          this.map.addOverlay(new this.BMap.Marker(point))
          this.mapCenter.lng = point.lng
          this.mapCenter.lat = point.lat
          this.mapZoom = 15
        }
      }
    }
  }
</script>

<style>
  .bm-view {
    margin-left: -10px;
    width: 100vw;
    height: 79vh;

  }
</style>
